<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('编码')" prop="code">
            <el-input v-model="form.code" :placeholder="$t('编码')" show-word-limit maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('名称')" prop="code">
            <el-input v-model="form.name" :placeholder="$t('名称')" show-word-limit maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('去重字段')" prop="distinctField">
            <el-select v-model="form.distinctField">
              <el-option v-for="field in form.fieldList" :key="field.id" :value="field.name" :label="$t(field.remark)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分组字段')" prop="groupField">
            <el-select v-model="form.groupField">
              <el-option v-for="field in form.fieldList" :key="field.id" :value="field.name" :label="$t(field.remark)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('Sql脚本')" prop="searchSql">
            <textarea ref="searchSql" v-model="form.searchSql" class="codesql" style="height:200px;width:600px;" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('字段列表') }}</span>
        <span style="float: right;font-size: 14px;">
          <template>
            <el-button v-hasPermi="['system:search:edit']" type="primary" size="mini" @click="getColumnBySql">{{ $t('刷新') }}</el-button>
          </template>
        </span>
      </div>
      <el-table
        :data="form.fieldList"
        border
        class="nowrapTable formTable"
      >
        <el-table-column :label="$t('字段名称')" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('字段别名')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('字段别名') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.remark'" :rules="fieldListRules.remark">
              <el-input v-model="scope.row.remark" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字段类型')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('字段类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.type'" :rules="fieldListRules.type">
              <el-select v-model="scope.row.type" clearable :placeholder="$t('请选择')" style="width: 100%" @change="updateFormatValue(scope.row)">
                <el-option
                  v-for="field in filedTypeOptions"
                  :key="field.dictValue"
                  :label="$t(field.dictLabel)"
                  :value="field.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('格式化')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.type'">
              <el-input v-if="scope.row.type === 'RQ' || scope.row.type === 'JE'" v-model="scope.row.format" />
              <el-select v-if="scope.row.type === 'ZD'" v-model="scope.row.format" value="" clearable filterable :placeholder="$t('请选择')" style="width: 100%">
                <el-option
                  v-for="dict in dictOptions"
                  :key="dict.dictType"
                  :label="$t(dict.dictName)"
                  :value="dict.dictType"
                >
                  <span style="float: left">{{ dict.dictName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <!--<el-table-column :label="$t('打开页面" align="center">-->
        <!--</el-table-column>-->
        <!--<el-table-column :label="$t('页面参数" align="center">-->
        <!--</el-table-column>-->
        <el-table-column :label="$t('用户是否可见')" align="center" width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isShow"
              active-value="Y"
              inactive-value="N"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否在列表展示')" align="center" width="150">
          <template slot-scope="scope">
            <el-switch
              v-if="scope.row.isShow === 'Y'"
              v-model="scope.row.isDisplayedInList"
              active-value="Y"
              inactive-value="N"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否固定')" align="center" width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isFixed"
              active-value="Y"
              inactive-value="N"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('排序')" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sort" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('默认宽度')" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.width" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-hasPermi="['system:search:edit']" type="primary" @click="submitForm">{{ $t("保存") }}</el-button>
    </div>
  </div>
</template>

<script>
    import { saveSearchSqlBase, getSearchSqlBase, getColumnBySql } from '@/api/system/search/searchSqlBase'
    import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
    import 'codemirror/theme/ambiance.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/addon/hint/show-hint.css'

    const CodeMirror = require('codemirror/lib/codemirror')
    require('codemirror/addon/edit/matchbrackets')
    require('codemirror/addon/selection/active-line')
    require('codemirror/mode/sql/sql')
    require('codemirror/addon/hint/show-hint')
    require('codemirror/addon/hint/sql-hint')
    export default {
        name: 'CodeMirror',
        data() {
            return {
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
                // 字段类型字典
                filedTypeOptions: [],
                // 字典信息
                dictOptions: [],
                editor: {},
                // 表单校验
                rules: {
                  code: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  name: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  searchSql: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                fieldListRules: {
                  remark: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                  type: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
                }
            }
        },
        created() {
          this.getDicts('search_field_type').then(response => {
            this.filedTypeOptions = response.data
          })
          /** 查询字典下拉列表 */
          getDictOptionselect().then(response => {
            this.dictOptions = response.data
          })
        },
      mounted() {
        const mime = 'text/x-mariadb'
        // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
        this.editor = CodeMirror.fromTextArea(this.$refs.searchSql, {
          mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
          indentWithTabs: true,
          smartIndent: true,
          lineNumbers: true,
          matchBrackets: true,
          // theme: theme,
          // autofocus: true,
          extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
          hintOptions: { // 自定义提示选项
            tables: {
              users: ['name', 'score', 'birthDate'],
              countries: ['name', 'population', 'size']
            }
          }
        })

        this.editor.on('cursorActivity', function() {
          if (this !== null) {
            this.editor.showHint()
          }
        })
      },
        methods: {
            // 初始化数据
            init(data) {
                if (data != null && data.id !== undefined) {
                    this.loading = true
                    getSearchSqlBase(data.id).then(response => {
                        this.form = response.data
                        this.editor.setValue(this.form.searchSql !== null ? this.form.searchSql : '')
                         this.loading = false
                    })
                } else {
                    this.reset()
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                code: undefined,
                searchSql: undefined,
                fieldList: [],
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                  distinctField: undefined,
                  groupField: undefined
                }
                this.editor.setValue('')
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.form.searchSql = this.editor.getValue()
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveSearchSqlBase(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
           //
          getColumnBySql: function() {
            this.form.searchSql = this.editor.getValue()
            if (this.form.searchSql === null || this.form.searchSql === '') {
              this.$message.error('sql脚本不能为空')
            } else {
              getColumnBySql(this.form).then(response => {
                // 保存之前配置的数据
                var fieldTempMap = {}
                for (var j = 0; j < this.form.fieldList.length; j++) {
                  var filed = this.form.fieldList[j]
                  fieldTempMap[filed.name] = filed
                }
                var fieldList = []
                for (var i = 0; i < response.data.length; i++) {
                    var field = {}
                    if (fieldTempMap[response.data[i]] !== null && fieldTempMap[response.data[i]] !== undefined) {
                      field = fieldTempMap[response.data[i]]
                      field.sort = (i + 1) * 10
                    } else {
                      field.name = response.data[i]
                      field.remark = response.data[i]
                      field.type = 'WB'
                      field.isShow = 'Y'
                      field.isDisplayedInList = 'Y'
                      field.sort = (i + 1) * 10
                      field.width = 200
                    }
                    fieldList.push(field)
                }
                this.form.fieldList = fieldList
              })
            }
          },
          // 设置格式化字段默认值
          updateFormatValue: function(row) {
              if (row.type === 'JE') {
                row.format = '###,###.####'
              } else if (row.type === 'RQ') {
                row.format = 'yyyy-MM-dd'
              }
          }
        }
    }
</script>
<style scoped>
  .codesql {
    font-size: 11pt;
    font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
  }
</style>
